# -*- coding: utf-8 -*-
# @Time    : 2020/6/3 15:30
# @Author  : Elliott Zheng
# @Email   : admin@hypercube.top
# @File    : utils.py
# @Software: PyCharm

import json
import os
import datetime
import sys
from os import environ, path


def get_win_desktop():
    # reference https://blog.csdn.net/u013948858/article/details/75072873
    # 能够解决桌面路径被修改的问题
    import winreg

    key = winreg.OpenKey(
        winreg.HKEY_CURRENT_USER,
        r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders",
    )
    return winreg.QueryValueEx(key, "Desktop")[0]


def relative(x):
    if os.path.isabs(x):
        return x
    else:
        return os.path.abspath(path.join(sys.argv[0],"../", x))





def get_desktop_dir():
    if sys.platform == "win32":
        desktop_dir = get_win_desktop()
    elif sys.platform in ["linux", "darwin"]:
        if environ.get("TEST_DIR"):
            desktop_dir = environ.get("TEST_DIR")
        else:
            desktop_dir = path.join(environ["HOME"], "Desktop")
    else:
        print("{} version not implemented".format(sys.platform))
        raise NotImplementedError
    return desktop_dir


desktop_dir = get_desktop_dir()

ignore_key = "gleaner-ignore"
standby_key = "gleaner-standby"


def clear_layout(layout):
    while layout.count():
        child = layout.takeAt(0)
        if child.widget() is not None:
            child.widget().deleteLater()
        elif child.layout() is not None:
            clear_layout(child.layout())


def get_path(*args):
    return os.path.join(desktop_dir, *args)


def load_json(file):
    with open(file, "r") as f:
        res = json.load(f)
    return res


def save_json(file, obj):
    with open(file, "w", encoding="utf-8") as f:
        json.dump(obj, f, indent=4, ensure_ascii=False)


def get_time_str():
    curr_time = datetime.datetime.now()
    time_str = datetime.datetime.strftime(
        curr_time, "%Y-%m-%d-%H-%M-%S"
    )  # 2019-07-06-15-50-12
    return time_str
